package com.tianji.promotion.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.config.constans.PromotionsContans.COUPON_CODE_SERIAL_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author wangyuqing
 * @since 2024-09-01
 */
@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final StringRedisTemplate redisTemplate;

    /**
     * 1.生成兑换码
     *
     * @param coupon
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    public void asyncGenerateCode(Coupon coupon) {
        //1.生成自增序列号
        BoundValueOperations<String, String> operations = redisTemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
        //1.1获取自增数量为优惠券的发放数量
        Integer totalNum = coupon.getTotalNum();
        //1.2获取最大的自增序列号
        Long result = operations.increment(totalNum);
        try {
            if (result == null) {
                return;
            }
            int maxSerialNum = result.intValue();
            //2.生成兑换码
            List<ExchangeCode> list = new ArrayList<>(totalNum);
            for (int serialNum = maxSerialNum - totalNum + 1; serialNum <= maxSerialNum; serialNum++) {
                String code = CodeUtil.generateCode(coupon.getId(), serialNum);
                //3.保存到数据库
                ExchangeCode exchangeCode = new ExchangeCode();
                exchangeCode.setId(serialNum);
                exchangeCode.setCode(code);
                exchangeCode.setExchangeTargetId(coupon.getId());
                exchangeCode.setExpiredTime(coupon.getTermEndTime());
                list.add(exchangeCode);
            }
            saveBatch(list);
        } catch (Exception e) {
            if (ObjectUtil.isNotEmpty(result)) {
                operations.decrement(totalNum);
            }
            e.printStackTrace();
            throw new BizIllegalException("");
        }
    }
}
